#include "io_utils.h"
#include "QQRealStreamTcp.h"
#include "TG_DATA_DEF.h"

RealStreamTcp::RealStreamTcp()
{
}

RealStreamTcp::~RealStreamTcp(void)
{
	CRealStreamItem::UnInitialize();
}


int RealStreamTcp::RecvNetPacket(NET_PACKET *pPacket)
{
	NET_PACKET_HEAD *pHead = &pPacket->xPacketHead;
	char            *pData = (char*)pPacket->cPacketData;

	int nRecLen = r_read (CRealStreamItem::m_hSocket,(char*)pHead,sizeof(NET_PACKET_HEAD));

	//printf("nDataLen:%d,nFrameNum:%d,nMsgType:%x \n",pHead->nDataLen,pHead->nFrameNum,pHead->nMsgType);

	if( nRecLen != sizeof(NET_PACKET_HEAD))
	{
		return TG_ERR_FAILURE;
	}
	if( FALSE == pHead->CheckCRC())
	{
		return TG_ERR_FAILURE;
	}
	if( pHead->nDataLen > NET_PACKET_SIZE ||
		pHead->nFrameSize > MAX_FRAME_SIZE  ||
		pHead->nPacketNum > ( ((pHead->nFrameSize+NET_PACKET_SIZE-1)/NET_PACKET_SIZE) )
	  )
	{
		return TG_ERR_FAILURE;
	}

	if( r_read(  CRealStreamItem::m_hSocket,pData,pHead->nDataLen)!=pHead->nDataLen)
	{
		return TG_ERR_FAILURE;
	}

	return TG_ERR_SUCCESS;
}


int RealStreamTcp::vTranslateRecv()
{
	int nErrCode = 0;
	NET_PACKET_HEAD *pPacketHead = &m_xRecvPacket.xPacketHead;
	UINT8           *pPacketData = (UINT8*)m_xRecvPacket.cPacketData;

	if( TG_ERR_SUCCESS != (nErrCode = RecvNetPacket(&m_xRecvPacket) ) )
	{
		if( TG_ERR_NETWORK_ERRORDATA == nErrCode )
		{
			return TG_ERR_SUCCESS;
		}
		return TG_ERR_NETWORK_RECV_ERROR;
		//return TG_ERR_SUCCESS;
	}
 
	if( pPacketHead->nMsgType > 0xff ) //��������
	{
		return TG_ERR_SUCCESS;
	}

	CRealStreamItem::m_nRecvPacketCount++;

	tagFrame *pActiveFrame = m_pEndFrame;
	if( 0 == pPacketHead->nPacketNum )
	{
		pActiveFrame->nPriority     = pPacketHead->nPriority;
		pActiveFrame->nFrameType    = (UINT8)pPacketHead->nMsgType;
		pActiveFrame->nFrameNum     = pPacketHead->nFrameNum;
		pActiveFrame->nFrameSize    = pPacketHead->nFrameSize;
		pActiveFrame->nValidFrmSize = 0;
		pActiveFrame->nFrameID      = pPacketHead->nFrameID;
		pActiveFrame->nPacketCount  = (pPacketHead->nFrameSize + NET_PACKET_SIZE - 1)/NET_PACKET_SIZE;
		pActiveFrame->nTimeStamp    = ( (TG_FRAME_HEAD *)pPacketData )->nTimeStamp;
	}

	pActiveFrame->nValidFrmSize += pPacketHead->nDataLen;

	UINT8 *pDataTemp = m_xDataBlock.pBuffer + NET_PACKET_SIZE * pPacketHead->nPacketNum;
	memcpy( pDataTemp,pPacketData,pPacketHead->nDataLen );

	if( pActiveFrame->nFrameSize == pActiveFrame->nValidFrmSize )
	{
		UINT8 *pFrame = m_xDataBlock.pBuffer;
		m_funCallBack( pFrame,pActiveFrame->nFrameSize,m_nContext,m_pContext );
	}

	return 0;
}
